package com.hdy.oa.web.action.department;

import com.hdy.DBUtils.JDBC;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

@WebServlet("/dept/delete")
public class DepDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        String deptNo = request.getParameter("deptNo");

        Connection connection=null;
        PreparedStatement ps=null;
        int count=0;

        try {

            connection= JDBC.getConnection();
            connection.setAutoCommit(false);
            String sql="delete from dept where DEPTNO=?";
            ps=connection.prepareStatement(sql);
            ps.setString(1,deptNo);
            count=ps.executeUpdate();
            connection.commit();
        } catch (SQLException e) {
            try {
                if(connection!=null){
                    connection.rollback();
                }
            } catch (SQLException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }finally {
            JDBC.close(connection,ps,null);
        }
        String contextPath = request.getContextPath();
        if(count==1){
           // request.getRequestDispatcher("/dept/list").forward(request,response);
            response.sendRedirect(contextPath+"/dept/list");
        }else{
            out.print("alert('删除失败！')");
            //request.getRequestDispatcher("/error.html").forward(request,response);
            response.sendRedirect(contextPath+"/error.html");
        }


    }
}
